import { createStore } from 'vuex'
import { authApi } from '../request/auth.js'
import { userApi } from '../request/user.js'
import { systemApi } from '../request/system.js'
import { API_CONFIG } from '@/config/api.js'

// 用户模块
const user = {
    namespaced: true,
    state: {
        // usdtBalance: uni.getStorageSync('usdtBalance') || '0.00',
        // goldBalance: uni.getStorageSync('goldBalance') || '0.00',
        // token: uni.getStorageSync('x-token') || '',
        // userInfo: uni.getStorageSync('userInfo') || {},
        usdtBalance: '0.00',
        goldBalance: '0.00',
        token: '',
        userInfo: {},
        friendHomeMode: false,
        languagePack: {},
        currentLanguage: 'en-US', // 当前语言
    },
    mutations: {
        SET_USDT_BALANCE(state, usdtBalance) {
            state.usdtBalance = usdtBalance
            uni.setStorageSync('usdtBalance', usdtBalance)
        },
        SET_GOLD_BALANCE(state, goldBalance) {
            state.goldBalance = goldBalance
            uni.setStorageSync('goldBalance', goldBalance)
        },
        SET_TOKEN(state, token) {
            state.token = token
            uni.setStorageSync('x-token', token)
        },
        SET_USER_INFO(state, userInfoRes) {
            // console.log('SET_USER_INFO', userInfoRes)
            state.userInfo = userInfoRes
            uni.setStorageSync('userInfo', userInfoRes)
        },
        SET_USER_AVATAR(state, avatar) {
            state.userInfo.avatar = avatar
            uni.setStorageSync('userInfo', state.userInfo)
        },
        SET_NICK_NAME(state, name) {
            state.userInfo.nick_name = name
            uni.setStorageSync('userInfo', state.userInfo)
        },
        SET_USER_LEVEL(state, level) {
            state.userInfo.level = level
            uni.setStorageSync('userInfo', state.userInfo)
        },
        SET_USER_COIN(state, coin) {
            state.userInfo.coin = coin
            uni.setStorageSync('userInfo', state.userInfo)
        },
        SET_USER_USDT_BALANCE(state, usdt_balance) {
            state.userInfo.usdt_balance = usdt_balance
            uni.setStorageSync('userInfo', state.userInfo)
        },
        SET_USER_RECOMMEND_CODE(state, recommend_code) {
            state.userInfo.recommend_code = recommend_code
            uni.setStorageSync('userInfo', state.userInfo)
        },
        CLEAR_USER_DATA(state) {
            state.token = ''
            state.userInfo = {}
            uni.removeStorageSync('x-token')
            uni.removeStorageSync('userInfo')
        },
        SET_IS_VIEW_FRIEND_HOME(state, friendHomeMode) {
            state.friendHomeMode = friendHomeMode
        },
        SET_LANGUAGE_PACK(state, languagePack) {
            state.languagePack = languagePack
        },
        SET_CURRENT_LANGUAGE(state, language) {
            state.currentLanguage = language
            uni.setStorageSync('currentLanguage', language)
        }
    },
    actions: {
        setToken({ commit }, token) {
            commit('SET_TOKEN', token)
        },
        async loadLanguagePack({ commit }) {
            try {
                const res = await systemApi.getLanguagePack()
                if (res && res.code === 200 && Array.isArray(res.data)) {
                    // 将语言包数据转换为Map格式以便快速查找
                    const languageMap = {}
                    res.data.forEach(item => {
                        if (item.languageKey && item.description) {
                            languageMap[item.languageKey] = item.description
                        }
                    })
                    commit('SET_LANGUAGE_PACK', languageMap)
                    console.log('语言包加载成功，共', Object.keys(languageMap).length, '条记录')
                    return languageMap
                }
            } catch (error) {
                console.error('加载语言包失败:', error)
            }
            return {}
        },
        async setUserInfo(context, userInfo) {
            context.commit('SET_USER_INFO', userInfo)
            if (userInfo.avatar) {
                if (userInfo.avatar.includes('profile')) {
                    userInfo.avatar = API_CONFIG.BASE_URL + userInfo.avatar
                } else {
                    const res = await userApi.getAvatar(userInfo.avatar)
                    if (res.code === 200) {
                        userInfo.avatar = res.data
                    }
                }
            }
        },
        async getUserInfo({ commit }) {
            const res = await userApi.getUserInfo()
            if (res.code === 200) {
                const userInfo = res.data
                commit('SET_USER_INFO', userInfo)
                if (userInfo.avatar) {
                    if (userInfo.avatar.includes('profile')) {
                        userInfo.avatar = API_CONFIG.BASE_URL + userInfo.avatar
                    } else {
                        try {
                            const res = await userApi.getAvatar(userInfo.avatar)
                            if (res.code === 200) {
                                this.setUserAvatar(res.data)
                            }
                        } catch (err) {
                            console.log('get_avatar error', err)
                        } finally {}
                    }
                }
            }
        },
        setUserAvatar({ commit }, avatar) {
            console.log('upload avatar', avatar)
                // const res = await userApi.getAvatar(avatar)
                // if (res.code === 200) {
            commit('SET_USER_AVATAR', API_CONFIG.BASE_URL + API_CONFIG.ENDPOINTS.FARM.GET_AVATAR + '?resource=' + avatar)
                // } else {
                //     uni.showToast({ title: res.msg, icon: 'none' })
                // }
        },
        setNickName({ commit }, name) {
            commit('SET_NICK_NAME', name)
        },
        setUserLevel({ commit }, level) {
            commit('SET_USER_LEVEL', level)
        },
        setUserCoin({ commit }, coin) {
            commit('SET_USER_COIN', coin)
        },
        setUserUsdtBalance({ commit }, usdt_balance) {
            commit('SET_USER_USDT_BALANCE', usdt_balance)
        },
        setUserRecommendCode({ commit }, recommend_code) {
            commit('SET_USER_RECOMMEND_CODE', recommend_code)
        },
        setFriendHomeMode({ commit }, friendHomeMode) {
            commit('SET_IS_VIEW_FRIEND_HOME', friendHomeMode)
        },
        async logout({ commit, state }) {
            try {
                // 如果有token，调用后端退出登录接口
                if (state.token) {
                    await authApi.logout()
                }
            } catch (error) {
                console.error('调用退出登录接口失败:', error)
                    // 即使接口调用失败，也要清除本地数据
            } finally {
                // 清除本地用户数据
                commit('CLEAR_USER_DATA')

                // 跳转到登录页
                uni.reLaunch({
                    url: '/pages/login/login'
                })
            }
        }
    },
    getters: {
        isLoggedIn: state => !!state.token,
        userInfo: state => state.userInfo,
        usdtBalance: state => state.usdtBalance,
        goldBalance: state => state.goldBalance,
        friendHomeMode: state => state.friendHomeMode,
        languagePack: state => state.languagePack,
        // 翻译函数
        translate: (state) => (languageKey, fallback = '') => {
            if (!languageKey) return fallback
            return state.languagePack[languageKey] || fallback || languageKey
        }
    }
}

// 应用模块
const app = {
    namespaced: true,
    state: {
        loading: false,
        networkStatus: true,
        systemConfig: {}
    },
    mutations: {
        SET_LOADING(state, loading) {
            state.loading = loading
        },
        SET_NETWORK_STATUS(state, status) {
            state.networkStatus = status
        },
        SET_SYSTEM_CONFIG(state, systemConfigList) {
            const systemConfig = {}
            systemConfigList.forEach(item => {
                systemConfig[item.configKey] = item.configVal
            })
            state.systemConfig = systemConfig
        }
    },
    actions: {
        setLoading({ commit }, loading) {
            commit('SET_LOADING', loading)
        },
        setNetworkStatus({ commit }, status) {
            commit('SET_NETWORK_STATUS', status)
        },
        async getSystemConfig({ commit }) {
            const res = await systemApi.getSystemConfig()
            if (res.code === 200) {
                commit('SET_SYSTEM_CONFIG', res.data)
            }
        }
    },
    getters: {
        systemConfig: state => state.systemConfig
    }
}

const store = createStore({
    modules: {
        user,
        app
    }
})

export default store